<?php

use console\db\Migration;
use yii\db\Query;

/**
 * 用户手机号信息加密
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class m300000_000013_t_user_meta_encrypt_mobile extends Migration {

    const BATCH_SIZE = 1000;

    /**
     * @inheritdoc
     */
    public $tableName = '{{%user_meta}}';

    /**
     * @inheritdoc
     */
    public function safeUp() {
        $query = (new Query())->from($this->tableName)->select([
            'id',
            'temp_mobile',
        ])->where([
            'and',
            ['IS NOT', 'temp_mobile', null],
            ['mobile' => null],
        ]);

        $this->handleProgress($query, [$this, 'evenDule']);
    }

    /**
     * 处理结果
     * @param Migration $migration
     * @param array $rows
     */
    public static function evenDule($migration, $rows) {
        foreach ($rows as $user) {
            $migration->db->createCommand()->update($migration->tableName, [
                'mobile' => static::encryptMobile($user['temp_mobile'])
            ], ['id' => $user['id']])->execute();
        }
    }

    /**
     * 加密手机号
     * @param string $mobile
     */
    private static function encryptMobile($mobile) {
        /* @var $security \common\base\Security */
        $security = Yii::$app->security;
        return $security->encryptMaster($mobile);
    }

}
